//
//  GPSTrainingViewController.swift
//  DaFit
//
//  Created by Paul on 2022/1/10.
//  Copyright © 2022 sylar. All rights reserved.
//

import Foundation
import CoreLocation
import UIKit
import RxCocoa
import RxSwift
import MYModule
import CRPSmartRing


open class TrainingTypeListController: ViewController {

    public let tableView = UITableView(frame: CGRect.zero, style: .plain)
    
    public var cells: [TrainingType] = []
    
    public var dataListArr = BehaviorSubject(value: [TrainingType]())
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationBar()
        
        getTrainingTypes()
    }
    
    open func getTrainingTypes() {
        
        self.cells = TrainingType.allTypes
        self.dataListArr.onNext(self.cells)

        let deviceInfo = DeviceInfo.current()
        if let trainingTypes = deviceInfo.trainingTypes {
            if !trainingTypes.isEmpty {
                cells = trainingTypes
                self.dataListArr.onNext(trainingTypes)
                return
            }
        }

        BluetoothManager.shared.getTrainingSupportList { list, error in

            var trainingTypes = list.compactMap { TrainingType.type(of: $0) }.filter { $0 != .unknown }
            // 排序
            trainingTypes = trainingTypes.sorted {
                
                if ($0.isGPS && !$1.isGPS) || (!$0.isGPS && $1.isGPS) {
                    return $0.rawValue > $1.rawValue
                }
                
                return $0.rawValue < $1.rawValue
                
            }
            
            
            deviceInfo.trainingTypes = trainingTypes
            deviceInfo.save()
            
            self.cells = trainingTypes
            self.dataListArr.onNext(trainingTypes)
            
        }
              
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barStyle = .black
        self.navigationController?.navigationBar.isHidden = true

        
    }
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        self.navigationController?.setNavigationBarHidden(false, animated: false)
        
    }
    
    open func navigationBar() {
        
        self.navigation.bar.tintColor = UIColor.assist_222222
        self.navigation.bar.barTintColor = UIColor.assist_FFFFFF
        self.navigation.item.title = "workouts_records_select_workout_title".language
        
       
        
    }
    
    
    @objc open func backToPrevious() {
        self.navigationController?.navigationBar.barStyle = .default
        _ = self.navigationController?.popViewController(animated: true)
    }
    
   
    open override func makeUI() {
        super.makeUI()
        
        self.view.backgroundColor = .white
        
        tableView.backgroundColor = .white
        tableView.estimatedRowHeight = 0
        tableView.rowHeight = 100
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        tableView.register(TrainingTypeTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(TrainingTypeTableViewCell.self))
        
        view.addSubview(tableView)
        
        let top: CGFloat = UIApplication.shared.statusBarFrame.height + self.navigation.bar.height
       
        tableView.snp.makeConstraints { make in
            
            make.top.equalToSuperview().offset(top)
            make.left.right.equalToSuperview()
          
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalToSuperview()
            }
        }
        
    
        dataListArr.asObserver().bind(to: tableView.rx.items(cellIdentifier: NSStringFromClass(TrainingTypeTableViewCell.self))) {tableView, type, cell in
            
            guard let cell = cell as? TrainingTypeTableViewCell else { return }
            
            cell.setImage(image: UIImage(named: type.iconName))
            cell.setTitle(title: type.title)
            
        }.disposed(by: rx.disposeBag)
        
        dataListArr.onNext(cells)
        
//        // 点击
        tableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in

            self?.toDetail(indexPath)

        }).disposed(by: rx.disposeBag)
    }
    
   open func toDetail(_ indexPath: IndexPath) {

        let row = indexPath.row
        if row > self.cells.count - 1 {
            return
        }
        let type = self.cells[row]
       
      
        if type.isGPS {
            presentToTrainingGPSMapController(type: type)
        } else {
            pushTrainingStrartController(type: type)
            
        }
    }
    
    
    /// 去GPS 锻炼
    /// - Parameter type: type
    open func presentToTrainingGPSMapController(type: TrainingType) {
        
        DispatchQueue.main.async {
            
            let vc = GPSTrainingCarryPhoneViewController()
            vc.type = type
            self.navigationController?.pushViewController(vc, animated: true)
            
        }
        
    }
    
    
    /// 去普通锻炼
    /// - Parameter type: type
    open func pushTrainingStrartController(type: TrainingType) {
        
        let vc = TrainningStartController()
        vc.type = type
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle{
        return UIStatusBarStyle.lightContent
    }
    
}


